<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>树洞聊天</title>
    <style>
        #chatroom {
            width: 280px;
            height: 420px;
            border: 1px solid #666;
            border-radius: 10px;
            padding: 10px;
            box-sizing: border-box;
            overflow: auto;
            color: #999;
        }

        .text {
            color: darkmagenta;
            font-size: 14px;

        }
    </style>
</head>

<body>
    <div>
        <h2>欢迎热烈聊天 </h2>
        <div id="chatroom">

        </div>
        <div>
            <input type="text" id="word" placeholder="聊天内容">
            <button id="sendbtn">点击发送</button>
        </div>
    </div>

    <script>
        window.onload = function () {
            const client = new WebSocket("ws://192.168.57.28:4800");

            client.onopen = function () {

                client.send("大家好,我是你们的一员.")
            }

            function sendToServer() {
                client.send(word.value)
                word.value = ''
            }
            sendbtn.onclick = sendToServer;

            document.onkeydown = function (e) {
                if (e.keyCode == 13) {
                    sendToServer()
                }
            }

            client.onmessage = function (msg) {
                console.log(msg)
                var chatroom = document.getElementById("chatroom")
                chatroom.innerHTML += `<p class="text"> ${msg.data} </p>`
            }

            client.onclose = function () {
                alert("socket 服务端已经异常关闭了")
            }
            client.onerror = function (err) {
                console.log('socket 服务器端已经 异常了 ' + err)
            }
        }
    </script>
</body>

</html>